package com.glsc.ngateway.platform.controller.it;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchSwitchDto;
import com.glsc.ngateway.common.api.platform.dto.it.SwitchBoardExport;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.it.SwitchService;
import com.glsc.ngateway.platform.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

import static com.glsc.ngateway.common.api.common.enums.Constant.SWITCH_ADMIN;

@RestController
@RequestMapping("/it/switch")
@Api(value = "交换机管理", tags = {"交换机管理"})
public class SwitchController {

    private static final Logger logger = LoggerFactory.getLogger(SwitchController.class);

    @Autowired
    private SwitchService switchService;

    @Autowired
    private UserCache userCache;
    @Autowired
    private UserService userService;

    @Value("${export.it}")
    public String itpath;


    @Autowired
    private HttpServletRequest request;

    // 查询交换机服务器列表
//    @RequestMapping(method = RequestMethod.GET, value = "query")
//    @ApiOperation(value = "查询交换机服务器列表", notes = "查询交换机服务器列表")
//    public PlatformResponseNew querySwitchList(
//            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
//            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
//        if (pageNo == null) {
//            pageNo = 1;
//        }
//        if (pageSize == null) {
//            pageSize = PageConstant.PageSize;
//        }
//        Page<List<Map<String, Object>>> result = switchService.querySwitchBoardList(pageNo, pageSize);
//        PlatformResponseNew ret = PlatformResponseNew.success();
//        ret.setData(result);
//        return ret;
//
//    }


    //搜索交换机服务器
    @RequestMapping(method = RequestMethod.POST, value = "search")
    @ApiOperation(value = "搜索交换机服务器", notes = "搜索交换机服务器")
    public PlatformResponse<Page<Map<String, Object>>> searchSwitchBoard(@RequestBody ParamSearchSwitchDto params) {
        if (params.getPageNo() == null) {
            params.setPageNo(PageConstant.PageNo);
        }
        if (params.getPageSize() == null) {
            params.setPageSize(PageConstant.PageSize);
        }
        PlatformUserDto user = userCache.get(request);
        String userId = user.getUserid();
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if ("itadmin".equals(user.getUsername()) || roleNames.contains("itadmin") || roleNames.contains(SWITCH_ADMIN)) {
            userId = null;
        }
        String userAccount = params.getUserAccount();
        if (StringUtils.isNotEmpty(userAccount)) {
            PlatformUserDto u = userService.findByUsername(userAccount);
            if (u != null) {
                userId = u.getUserid();
            }
        }

        String businessName = params.getBusinessName();
        String applicationDetail = params.getApplicationDetail();
        String ip1 = params.getIp1();
        String ip2 = params.getIp2();
        Integer virtualIp = params.getVirtualIp();
        String virtualName = params.getVirtualName();
        String machineCab = params.getMachineCab();
        Integer machineRoom = params.getMachineRoom();
        String switchIp = params.getSwitchIp();
        String macAddress = params.getMacAddress();
        String switchInterface = params.getSwitchInterface();

        if (StringUtils.isEmpty(params.getBusinessName())) {
            businessName = null;
        }
        if (StringUtils.isEmpty(params.getApplicationDetail())) {
            applicationDetail = null;
        }
        if (StringUtils.isEmpty(params.getVirtualName())) {
            virtualName = null;
        }
        if (StringUtils.isEmpty(params.getIp1())) {
            ip1 = null;
        }
        if (StringUtils.isEmpty(params.getIp2())) {
            ip2 = null;
        }
        if (StringUtils.isEmpty(params.getMachineCab())) {
            machineCab = null;
        }
        if (StringUtils.isEmpty(params.getSwitchInterface())) {
            switchInterface = null;
        }
        if (StringUtils.isEmpty(params.getSwitchIp())) {
            switchIp = null;
        }
        if (StringUtils.isEmpty(params.getMacAddress())) {
            macAddress = null;
        }
        if (params.getVirtualIp() == null || params.getVirtualIp() == 0) {
            virtualIp = null;
        }
        if (params.getMachineRoom() == null || params.getMachineRoom() == 0) {
            machineRoom = null;
        }

        Page<Map<String, Object>> result = switchService.searchSwitchBoard(params.getPageNo(), params.getPageSize(), businessName, applicationDetail,
                virtualName, ip1, ip2, machineRoom, machineCab, switchIp, switchInterface, macAddress, virtualIp, userId);
        return PlatformResponse.successData(result);
    }

    @RequestMapping(method = RequestMethod.POST, value = "export")
    @ApiOperation(value = "exportSwitchOutPut", notes = "exportSwitchOutPut")
    public ResponseEntity<byte[]> exportSwitchOutPut() throws IOException {
        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得导出权限，请联系管理员");
        /*验证新增权限end*/
        List<SwitchBoardExport> result = switchService.exportSwitchBoardOutPut();
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "交换机").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "switch.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }


//	//搜索交换机服务器名称
//	@RequestMapping(value = "/multiSearch", method = { RequestMethod.GET, RequestMethod.POST })
//	public Object multiSearchSwitchBoard( com.jlwang.rest.report.boundary.SwitchBoardAddOrUpdateInput input,
//			HttpServletRequest request, HttpServletResponse response) throws Exception {		
// 	Map<String, Object> switchBoardInfo = BeanUtil.bean2Map(input);
//
//	List<Map<String, Object>> result =	switchBoardService.multiSearch(switchBoardInfo);
//
//		JsonResult jsonResult = new JsonResult();
//		jsonResult.saveResultSet(result);        //保存搜索数据
//		return jsonResult;
//	}
//	
//	//导出excel
//	@RequestMapping(value = "/querySwitchBoardOutPut", method = { RequestMethod.GET, RequestMethod.POST })
//	public Object queryVirtualOutPut(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String switchRecord = (String) request.getParameter("switchRecord");
//		List<SwitchBoardExport> result = switchBoardService.querySwitchBoardOutPut(switchRecord);
//		ArrayList<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();
//		
//		WriteSheet sheet = EasyExcel.writerSheet(0, "服务器交换机对应表").build();
//		ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
//        multipleSheelPropety.setData(result);
//        multipleSheelPropety.setSheet(sheet);
//
//        list.add(multipleSheelPropety);
//
//        String fileName = "d:/fwqjhj.xlsx";
//        ExcelUtil.writeWithMultipleSheel(fileName,list);
//
//		response.setContentType("application/octet-stream");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//		
//		OutputStream output = response.getOutputStream();
//        byte[] bytes = FileUtil.readByteFromFilePath(fileName);
//        if (null == bytes) {
//            output.close();
//            return null;
//        }
//        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
//        int len;
//        byte[] buf = new byte[1024];
//        while ((len = in.read(buf)) != -1) {
//            output.write(buf, 0, len);
//        }
//        output.flush();
//        output.close();
//        return null;
//	}	
//	
//	//搜索服务器交换机对应表
//	@RequestMapping(value = "/searchSwitchBoard", method = { RequestMethod.GET, RequestMethod.POST })
//	public Object searchSwitchBoard(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String switchRecord = (String) request.getParameter("switchRecord");
//		List<Map<String, Object>> result = switchBoardService.searchSwitchBoard(switchRecord);
//
//		// 整理输出信息
//		JsonResult jsonResult = new JsonResult();
//		jsonResult.saveResultSet(result);
//		return jsonResult;
//	}

}
